package com.eqdd.yiqidian.ui.mine.space.fragment

import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.ProductBean
import com.eqdd.yiqidian.box.ItemDecoration.DividerLineItemDecoration
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.http.JsonConverter
import com.eqdd.yiqidian.kotlin.imgPathPreview
import com.eqdd.yiqidian.ui.companyspace.ProductInfoActivity
import com.eqdd.yiqidian.utils.ImageUtil
import com.lzy.okgo.OkGo
import com.lzy.okrx2.adapter.FlowableBody
import com.shizhefei.mvc.MVCCoolHelper
import io.reactivex.Flowable
import kotlinx.android.synthetic.main.fragment_company_space.view.*
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.support.v4.startActivity
import java.util.*

/**
 * Created by jhj on 18-7-4.
 */
class ProductFragment : Fragment() {


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_company_space, container, false)
        initView(view)
        return view
    }

    private var companyId: Int = -1

    private fun initView(view: View) {
        view.recyclerView.layoutManager = LinearLayoutManager(activity)
        view.recyclerView.addItemDecoration(DividerLineItemDecoration(activity))
        companyId = arguments?.getInt(Config.COMPANY_ID, -1) ?: -1
        if (companyId == -1) {
            return
        }
        var pageNum = 0
        val mvcHelper = MVCCoolHelper<List<ProductBean>>(view.coolRefreshView)
        val list = arrayListOf<ProductBean>()
        view.recyclerView.layoutManager = LinearLayoutManager(activity)
        view.recyclerView.addItemDecoration(DividerLineItemDecoration(activity))
        val slimAdapterEx = SlimAdapterEx.create().register<ProductBean>(R.layout.list_item_153, SlimInjector<ProductBean> { data, injector ->

            val span = SpannableString(String.format(Locale.CHINA, "价格：￥%s元", data?.productPrice))
            span.setSpan(ForegroundColorSpan(Color.RED), 3, span.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

            injector
                    ?.with<ImageView>(R.id.iv_image) { view ->
                        if (data?.image != null && "" != data.image) {
                            view.visibility = View.VISIBLE
                            view.onClick {
                                activity?.imgPathPreview(data.image)
                            }
                            Glide.with(activity)
                                    .asBitmap()
                                    .apply(ImageUtil.optionsNormal)
                                    .load(data.image)
                                    .into(object : SimpleTarget<Bitmap>() {
                                        override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>) {
                                            val scale = resource.width.toDouble() / resource.height.toDouble()
                                            if (scale < 0.85 && scale > 0.65) {
                                                view.scaleType = ImageView.ScaleType.CENTER_CROP
                                            }
                                            view.background = BitmapDrawable(resources, resource)

                                        }
                                    })
                        } else {
                            view.visibility = View.GONE
                        }
                    }
                    ?.text(R.id.tv_name, String.format(Locale.CHINA, "产品名称：%s", data?.productName))
                    ?.text(R.id.tv_post, String.format(Locale.CHINA, "产品类型：%s", data?.productType))
                    ?.text(R.id.tv_msg, span)
        }).attachTo(view.recyclerView).updateData(list as List<ProductBean>?) as SlimAdapterEx<ProductBean>?
        ItemClickSupport.addTo(view.recyclerView).setOnItemClickListener { recyclerView, position, v ->
            slimAdapterEx?.getDataItem(position)?.let {
                startActivity<ProductInfoActivity>(Config.ID to it.id,  "isVisitorSpace" to false, Config.COMPANY_ID to companyId)
            }
        }


        val dataSource = ModelRx2DataSource<ProductBean>(ModelRx2DataSource.OnLoadSource<ProductBean> { page, register ->
            pageNum = if (page == 1) 0 else pageNum
            OkGo.post<HttpResult<List<ProductBean>>>(HttpConfig.BASE_URL + HttpConfig.PRODUCT_LIST)
                    .params("companyId", companyId ?: 0)
                    .params("page", pageNum)
                    .converter(object : JsonConverter<HttpResult<List<ProductBean>>>() {
                        override fun test() {
                            super.test()
                        }
                    }).adapt(FlowableBody<HttpResult<List<ProductBean>>>())
                    .flatMap({ result ->
                        if (page == 1) {
                            mvcHelper.isAutoLoadMore = true
                        }
                        pageNum = result.page
                        Flowable.just<MutableList<ProductBean>>(if (result.items == null) ArrayList() else result.items as MutableList<ProductBean>?)
                    })
        }, 10)

        mvcHelper.setDataSource(dataSource)
        mvcHelper.adapter = slimAdapterEx
        mvcHelper.refresh()
    }


}